﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using StoreTransport.Business.Constants;
using StoreTransport.DAO;
using StoreTransport.Resources;
using StoreTransport.Business.Helper;
using StoreTransport.Data;
using StoreTransport.Business.Services;

namespace StoreTransport.Presentation.Forms {
    public partial class MarketTransportReportForm : Form {
        public bool DoStoreFirst { get; set; }
        private DataTable _data = null;
        List<MarketData> _dataList = new List<MarketData>();
        public MarketTransportReportForm() {
            InitializeComponent();
        }

        private void _btxShowReport_Click(object sender, EventArgs e) {
            if (!CommonHelper.IsValidDataToExport()) {
                MessageBox.Show(StoreTransportResource.ErrorMessage_InvalidInputToExport);
                return;
            }
            Cursor.Current = Cursors.WaitCursor;
            // get data
            StoreTransportDataContext context = CommonHelper.GetContext();
            ProductLine pl = (ProductLine)_drpProductLine.SelectedItem;
            List<MarketData> markets = new List<MarketData>();
          //  List<MarketDTO> rs = CalculatorService.BalanceProductBetweenMarkets(markets, pl, false);

           // rs = rs.OrderBy(m => m.RegionName).OrderBy(m => m.AreaName).ToList();
           // _dataList.AddRange(rs);
            buildReport();
            Cursor.Current = Cursors.Default;
        }

        private void buildReport2()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("Ten Sieu Thi");
            foreach (MarketData m in _dataList)
            {

            }

        }

        private void buildReport()
        {
            // Selected Region List
            //List<int> selectedRegionID = new List<int>();
            //foreach (TreeNode node in _tvwRegion.Nodes) {
            //    if (node.Checked) {
            //        selectedRegionID.Add(int.Parse(node.Text));
            //    }
            //}
            //DataTable dt = new DataTable();
            //dt.Columns.Add(StoreTransportResource.ProductCode);
            //dt.Columns.Add(StoreTransportResource.ProductName);
            //dt.Columns.Add(StoreTransportResource.FromMarket);
            //dt.Columns.Add(StoreTransportResource.ToMarket);
            //dt.Columns.Add(StoreTransportResource.QuantityTransport);
            //Dictionary<int, long> data = new Dictionary<int, long>();
            //foreach (MarketDTO m in _dataList)
            //{
            //    foreach (string id in m.CalProducts.Keys)
            //    {
            //        ProductDTO p = m.CalProducts[id];
            //        if (p.Transports1.Count > 0)
            //        {
            //            foreach (TransportDTO t in p.Transports1)
            //            {
            //                if (t.number1 > 0)
            //                {
            //                    int col = 0;
            //                    DataRow row = dt.NewRow();
            //                    row[col++] = p.ProductCode;
            //                    row[col++] = p.ProductName;
            //                    row[col++] = t.marketName;
            //                    row[col++] = m.MarketName;
            //                    row[col++] = t.number1;
            //                    dt.Rows.Add(row);
            //                }
            //            }
            //        }
            //    }
            //}
            //dt.DefaultView.Sort = StoreTransportResource.ProductCode + " ASC";
            //_grdvReport.DataSource = CommonHelper.FlipDataTable(dt);
            //_grdvReport.DoubleBuffered(true);
            //_grdvReport.Columns[0].Frozen = true;
            //_data = dt;
        }

        private void _btnExportReport_Click(object sender, EventArgs e) {
            ExportMarketReportList();
        }

        private void MarketTransportReportForm_Load(object sender, EventArgs e) {
            _drpProductLine.Select();
            InitRegionTreeview();
            _drpProductLine.DisplayMember = ColumnName.ProductLineName;
            _drpProductLine.ValueMember = ColumnName.ID;
            _drpProductLine.DataSource = CommonHelper.GetContext().ProductLines.OrderBy(c => c.ProductLineName);
            if (_drpProductLine.Items.Count > 0) {
                UpdateProductKindDropDown(CommonHelper.GetContext(), (_drpProductLine.SelectedItem as ProductLine).ID);
            }
            if (DoStoreFirst) {
                _pnlMarketTransport.Text = StoreTransportResource.ReportStoreMarketTransport;
                Report.Text = StoreTransportResource.ReportStoreMarketTransport;
                this.Text = StoreTransportResource.ReportStoreMarketTransport;
            }
        }

        private void ExportMarketReportList() {
            // New FolderBrowserDialog instance
            string chosenFolder = Application.StartupPath;
            FolderBrowserDialog Fld = new FolderBrowserDialog();
            // Set initial selected folder
            Fld.SelectedPath = chosenFolder;
            // Show the "Make new folder" button
            Fld.ShowNewFolderButton = true;
            if (Fld.ShowDialog() == DialogResult.OK) {
                // Select successful
                chosenFolder = Fld.SelectedPath;
            }
            _lblWaitingMessage.Text = StoreTransportResource.Message_Exporting;
            _lblWaitingMessage.Visible = true;
            string fileparten = string.Empty;
            if (DoStoreFirst) {
                fileparten = StoreTransportResource.StoreResultExportFileParten;
            } else { 
                fileparten = StoreTransportResource.MarketExportFileParten;
            }
            if (_data == null) {
                MessageBox.Show(StoreTransportResource.ErrorMessage_NoDataToExport);
                return;
            }
            string message = ExcelHelper.ExportData(_data, false, chosenFolder, fileparten);
            _lblWaitingMessage.Visible = false;
            if (!string.IsNullOrEmpty(message)) {
                MessageBox.Show(message);
            } else {
                MessageBox.Show(StoreTransportResource.Message_ExportingFinihed);
            }
        }

        private void InitRegionTreeview() {
            StoreTransportDataContext context = CommonHelper.GetContext();
            var regionList = context.Regions.OrderBy(c => c.RegionName);
            foreach (var region in regionList) {
                _tvwRegion.Nodes.Add(region.ID.ToString(), region.RegionName);
                _tvwRegion.Nodes[_tvwRegion.Nodes.Count - 1].Checked = true;
            }
        }

        private void _drpProductLine_SelectedIndexChanged(object sender, EventArgs e) {
            ProductLine pl = (ProductLine)_drpProductLine.SelectedItem;
            UpdateProductKindDropDown(CommonHelper.GetContext(), pl.ID);
            UpdateLastImportInfo(pl.ProductLineName);
        }

        private void UpdateLastImportInfo(string plName) {
            DateTime lastUpdateDate = CommonHelper.CurrentProductLine.LastUpdatedDate;
            if (lastUpdateDate != DateTime.MinValue) {
                _lblImportDate.Text = lastUpdateDate.ToShortDateString();
            } else {
                _lblImportDate.Text = StoreTransportResource.Message_ProductLineDataNotFound;
            }
        }

        private void UpdateProductKindDropDown(StoreTransportDataContext context, int productLineId) {
            _drpProductKind.Text = string.Empty;
            _drpProductKind.DisplayMember = ColumnName.ProductKindName;
            _drpProductKind.ValueMember = ColumnName.ID;
            _drpProductKind.DataSource = context.ProductKinds.Where(c => c.ProductLine == productLineId)
                .OrderBy(pk => pk.ProductKindName);
        }
    }
}
